package com.lagou.config;

import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.pojo.SqlCommandType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XmlMapperBuilder {
    private final Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream rs) throws DocumentException {
        Document document = new SAXReader().read(rs);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        configurationElement(namespace, rootElement);
        bindMapperForNamespace(namespace);
    }

    private void bindMapperForNamespace(String namespace) {
        Class<?> boundType = null;
        try {
            boundType = Resources.classForName(namespace);
        } catch (ClassNotFoundException e) {
            // 忽略，mapper不必须的，可以直接使用sqlSession
        }
        if (boundType != null && !this.configuration.hasMapper(boundType)) {
            this.configuration.addMapper(boundType);
        }
    }

    private void configurationElement(String namespace, Element rootElement) {
        parseStatementNodes(namespace, rootElement, "//select", SqlCommandType.SELECT);
        parseStatementNodes(namespace, rootElement, "//insert", SqlCommandType.INSERT);
        parseStatementNodes(namespace, rootElement, "//update", SqlCommandType.UPDATE);
        parseStatementNodes(namespace, rootElement, "//delete", SqlCommandType.DELETE);
    }

    private void parseStatementNodes(String namespace,
                                     Element rootElement,
                                     String expression,
                                     SqlCommandType sqlCommandType) {
        List<Element> list = rootElement.selectNodes(expression);
        for (Element element : list) {
            String id = element.attributeValue("id");
            String parameterType = element.attributeValue("parameterType");
            String resultType = element.attributeValue("resultType");
            String sql = element.getTextTrim();
            String statementId = namespace + "." + id;
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(statementId);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sql);
            mappedStatement.setSqlCommandType(sqlCommandType);
            this.configuration.getMappedStatementMap().put(statementId, mappedStatement);
        }
    }
}
